/*!
 * \file jxbankc_header.c
 *
 * \brief JXBANKC消息头操作
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2017/04/19
 *
 */

#include <stdio.h>
#include <ctype.h>

#include "frct_comm.h"

#include "jxbankc_comm.h"
#include "jxbankc_header.h"
#include "config.h"

int jxbankc_header_detect(char *p_payload
                        , unsigned int ui_payload_len)
{
    JXBANKC_PRINT_INFO("jxbankc_header_detect...\n");
    int i_loop = 0;
    int i_offset = 36;

    if (ui_payload_len < APM_JXBANKC_HDR_LEN)
        goto unknown;

    for (; i_loop < 11; i_loop++)
    {
        if (!isdigit(*(p_payload + i_loop)))
            goto unknown;
    }

    // 校验第12-37个字节是否为空白字符
    if (memcmp(p_payload + 11,
               "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
               25) != 0)
        goto unknown;

    for (; i_offset < APM_JXBANKC_HDR_LEN; i_offset += + 31)
    {
        if (*(p_payload + i_offset + 20) != 0x00)
        {
            for (i_loop = 0; i_loop < 11; i_loop++)
            {
                if (!isdigit(*(p_payload + i_offset + 20 + i_loop)))
                    goto unknown;
            }
        }
        else
            break;
    }

    return APM_L7_IS_YES;
unknown:
    return APM_L7_IS_UNKNOWN;
}

int jxbankc_header_unpack(char *p_payload
                        , unsigned int ui_payload_len
                        , Jxbankc_header *p_st_jxbankc_header)
{
    char arr_len[11+1] = {0x00};
    unsigned long long ull_len = 0LL;

    if (ui_payload_len < APM_JXBANKC_HDR_LEN)
        goto error;

    memset(arr_len, 0x00, sizeof(arr_len));
    strncpy(arr_len, p_payload, 11);
    ull_len = strtoull(arr_len, NULL, 10);

    p_st_jxbankc_header->ui_header_len = APM_JXBANKC_HDR_LEN;
    p_st_jxbankc_header->ui_pkt_len = (unsigned int) ull_len;

    return FR_SUCC;
error:
    return FR_FAIL;
}
